package cn.ty.utils;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 是MAC地址！不是Macintosh！
 */
public class MacUtil {

	/**
	 * @return XX-XX-XX-XX-XX-XX 格式，获取本机MAC地址
	 */
	public static String getMacAddressString() throws SocketException {
		byte[] bytes = getMacAddress();
		if (bytes.length > 0) {
			StringBuffer sb = new StringBuffer();
			for (byte b : bytes) {
				//与11110000作按位与运算以便读取当前字节高4位
				sb.append(Integer.toHexString((b & 240) >> 4));
				//与00001111作按位与运算以便读取当前字节低4位
				sb.append(Integer.toHexString(b & 15));
				sb.append("-");
			}
			sb.deleteCharAt(sb.length() - 1);
			return sb.toString().toUpperCase();

		} else {
			return null;
		}
	}

	public static byte[] getMacAddress() throws SocketException {
		Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces();
		while (ni.hasMoreElements()) {
			NetworkInterface netI = ni.nextElement();
			byte[] bytes = netI.getHardwareAddress();
			if (netI.isUp() && bytes != null && bytes.length == 6) {
				return bytes;
			}
		}
		return new byte[0];
	}
}
